package 网络编程.UDP协议.网络聊天室;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class 接收数据 {
    public static void main(String[] args) throws IOException {
        //1.创建接收数据的UDP平台端口
        DatagramSocket ds=new DatagramSocket(5564);

        //2.发送数据
        //创建接收数据的包DatagramPacket
        while (true){
            //创建接收数据的缓冲字节数组
            byte[] bytes = new byte[1024];
            DatagramPacket dp=new DatagramPacket(bytes,bytes.length);
            //发送数据
            ds.receive(dp);
            //3.解析数据
            byte[] data = dp.getData();
            int port = dp.getPort();
            InetAddress address = dp.getAddress();
            //获取接收到的数据长度
            int len = dp.getLength();
            System.out.println("对象发来了一条消息:"+new String(data,0,len));
            System.out.println("对方的设备名字是:"+address+",端口号是:"+port);
            if (new String(data,0,len).equals("886")){
                break;
            }
        }

        //4.释放资源
        ds.close();
    }
}
